<template>
  <div class="page">
    <van-nav-bar
      title="存奶管理"
      right-text="存入"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRigth"
    />
    <van-loading v-if="pageLoading" class="loading" type="spinner" color="#1989fa">加载中...</van-loading>

    <!-- 搜索组件 -->
    <!-- <van-search
      v-model="key"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search> -->
    <div v-else>
      <div class="topShowDiv">
        <div class="crileItem" @click="clickPicture(1)">
          <van-circle v-model="normal_currentRate" :rate="rateInfo.normalRate" color="#07c160" :clockwise="false" :stroke-width="80" :speed="100" :text="normal_text" />
          <br><span class="crileItem_span">正常 </span>
          <br><span class="crileItem_span_ML">({{ rateInfo.normalMl }}毫升)</span>
        </div>
        <div class="crileItem" @click="clickPicture(2)">
          <van-circle v-model="coming_currentRate" :rate="rateInfo.comingRate" color="#ff976a" :clockwise="false" :stroke-width="80" :speed="100" :text="coming_text" />
          <br><span class="crileItem_span">临期</span>
          <br><span class="crileItem_span_ML">({{ rateInfo.comingMl }}毫升)</span>
        </div>
        <div class="crileItem" @click="clickPicture(3)">
          <van-circle v-model="expired_currentRate" :rate="rateInfo.expiredRate" color="#ee0a24" :clockwise="false" :stroke-width="80" :speed="100" :text="expired_text" />
          <br><span class="crileItem_span">已过期</span>
          <br><span class="crileItem_span_ML">（{{ rateInfo.expiredMl }}毫升）</span>
        </div>
      </div>
      <van-tabs v-model="filter.milkStatus" swipeable animated sticky @change="getList()">
        <van-tab :name="0">
          <template #title> 全部({{ rateInfo.total }}) </template>
        </van-tab>
        <van-tab title="正常" :name="1">
          <template #title> 正常({{ rateInfo.normal }}) </template>
        </van-tab>
        <van-tab title="临期" :name="2">
          <template #title> 临期({{ rateInfo.coming }}) </template>
        </van-tab>
        <van-tab title="已过期" :name="3">
          <template #title> 已过期({{ rateInfo.expired }}) </template>
        </van-tab>
        <van-tab title="已用完" :name="4">
          <template #title> 已用完({{ rateInfo.useOve }}) </template>
        </van-tab>
      </van-tabs>
      <van-dropdown-menu active-color="#1989fa">
        <van-dropdown-item v-model="filter.order" :options="orderList" @change="getList()" />
      <!-- <van-dropdown-item v-model="filter.milkStatus" :options="milkStatusList" @change="getList()" /> -->
      </van-dropdown-menu>
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <div class="listDiv">
          <van-cell v-if="list.length > 0">
            <!-- 下拉刷新 -->

            <!-- 滑动单元格 -->
            <van-swipe-cell v-for="item in list" :key="item.id">
              <van-cell :border="true" is-link arrow-direction="down" :value="item.milkDate" @click="showDetail(item)">
                <template #title>
                  <span class="cell_title">编号：{{ item.id }} </span>
                  <van-tag v-if="item.milkStatus === 1" type="success ">正常</van-tag>
                  <van-tag v-else-if="item.milkStatus === 2" type="warning">临期</van-tag>
                  <van-tag v-else-if="item.milkStatus === 3" type="danger">过期</van-tag>
                  <van-tag v-else-if="item.milkStatus === 4" type="primary">已用完</van-tag>
                </template>

                <template #label>
                  <div>
                    <span class="cell_label">剩余容量：{{ item.capacity }} ml</span>
                  </div>
                  <div>
                    <span class="cell_label">总容量：{{ item.totalCapacity }} ml</span>
                  </div>
                  <div>
                    <span class="cell_label">已使用：{{ item.useCapacity }} ml</span>
                  </div>
                  <div>
                    <span class="cell_label">储存天数：{{ item.remainingDays }} 天</span>
                  </div>
                </template>
              </van-cell>
              <template #right>
                <van-button class="right_btn" square type="primary" text="使用" @click="showUseMilkFun(item)" />
                <van-button class="right_btn" square type="danger" text="删除" @click="deleteMilk(item)" />
              </template>
            </van-swipe-cell>
            <!-- 分页组件 -->
            <van-pagination v-model="currentPage" :page-count="total" @change="nextPage" />


          </van-cell>
          <van-empty
            v-else
            class="custom-image"
            image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
            description="暂无数据"
          />

        </div>
      </van-pull-refresh>
    </div>
    <van-dialog
      v-model="showUseMilk"
      title="使用存奶"
      show-cancel-button
      :before-close="beforeClose"
      @confirm="useMilk"
      @cancel="clossUseMilk"
    >
      <van-cell-group>
        <van-field v-model="milkInfo.capacityShow" readonly is-link label="使用容量" placeholder="请选择容量" @click="openMlChoose()" />

      </van-cell-group>
    </van-dialog>

    <van-dialog
      v-model="showAddMilk"
      title="存奶"
      show-cancel-button
      :before-close="beforeClose"
      @confirm="addMilk"
      @cancel="clossAddMilk"
    >
      <van-cell-group>
        <!-- <van-cell is-link title="选择存奶时间" :value="milkInfo.milkDate" @click="showDatePicker = true" /> -->
        <van-field v-model="milkInfo.milkDate" readonly is-link label="选择存奶时间" placeholder=" 请选择存奶时间" @click="showDatePicker = true" />
        <van-field v-model="milkInfo.capacityShow" readonly is-link label="容量" placeholder="请选择容量" @click="openMlChoose()" />

      </van-cell-group>
    </van-dialog>

    <van-popup v-model="showDatePicker" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showDatePicker = false"
        @confirm="chooseAddTime"
      />
    </van-popup>

    <van-popup v-model="showMilkMLPicker" position="bottom" :style="{ height: '30%' }">
      <van-picker
        title="存奶容量"
        show-toolbar
        :default-index="indexML"
        :columns="milkCapacityList"
        @confirm="onConfirm"
        @cancel="onCancel"
      />
    </van-popup>

    <van-dialog
      v-model="showAddAgain"
      :message="againMsg"
      show-cancel-button
      :before-close="beforeClose"
      @confirm="confirmAddAgain"
      @cancel="closeAddAgain"
    />

  </div>
</template>

<script>
import { Dialog, Toast } from 'vant'
import { getMilkInfoList, addMilkInfo, deletedMilkInfo, useMilk } from '@/api/milk.js'
export default {
  name: 'MilkIndex',
  data: function() {
    return {
      msg: '存奶管理主页',
      active: 'home',
      loadingList: false,
      pageLoading: true,
      normal_currentRate: 0,
      coming_currentRate: 0,
      expired_currentRate: 0,
      rateInfo: {
        normal: 0,
        coming: 0,
        expired: 0,
        useOve: 0,
        normalRate: 0,
        comingRate: 0,
        expiredRate: 0,
        useOveRate: 0
      },
      list: [],
      key: '',
      filter: {
        order: 1,
        milkStatus: 0
      },
      showAddMilk: false,
      showUseMilk: false,
      currentPage: 1,
      size: 6,
      total: 20,
      refreshing: false,
      milkInfo: {
        milkDate: '',
        capacity: null,
        capacityShow: ''
      },
      showMilkEdit: false,
      showDatePicker: false,
      showMilkMLPicker: false,
      minDate: new Date(2024, 5, 18),
      maxDate: new Date(),
      currentDate: new Date(),
      minML: 10,
      maxML: 240,
      indexML: 9,
      milkCapacityList: [],
      orderList: [
        { text: '存奶时间倒序', value: 0 },
        { text: '存奶时间正序', value: 1 }
      ],
      milkStatusList: [
        { text: '全部状态', value: 0 },
        { text: '正常', value: 1 },
        { text: '临期', value: 2 },
        { text: '已过期', value: 3 },
        { text: '已用完', value: 4 }
      ],
      addMilkId: null,
      showAddAgain: false,
      againMsg: ''
    }
  },
  computed: {
    normal_text() {
      return this.normal_currentRate.toFixed(0) + '%'
    },
    coming_text() {
      return this.coming_currentRate.toFixed(0) + '%'
    },
    expired_text() {
      return this.expired_currentRate.toFixed(0) + '%'
    }
  },
  // 进入页面前执行的钩子函数
  mounted() {
    this.getList()
    // console.log('班级页面渲染完成', this.list)
  },
  methods: {
    clickPicture(status) {
      this.filter.milkStatus = status
      this.currentPage = 1
      this.getList()
    },
    // 存奶容量弹窗方法
    openMlChoose() {
      this.milkCapacityList = []
      // 初始化选择列表
      for (let i = this.minML; i <= this.maxML; i += 10) {
        // console.log({ text: `${i}毫升`, value: i, disabled: false })
        this.milkCapacityList.push({ text: `${i}毫升`, value: i, disabled: false })
      }
      if (this.showUseMilk) {
        this.indexML = this.milkCapacityList.length - 1
      }
      // console.log(this.milkCapacityList)
      this.showMilkMLPicker = true
    },
    onConfirm(value, index) {
      // console.log(`当前值：${value.value}, 当前索引：${index}`)
      this.milkInfo.capacityChoose = value.value
      this.milkInfo.capacityShow = value.text
      this.showMilkMLPicker = false
    },
    onCancel() {
      // console.log('取消')
      this.showMilkMLPicker = false
    },
    // 点击顶部导航栏左侧
    onClickLeft() {
      this.$router.push('/home/index')
    },
    // 点击顶部导航栏右侧
    onClickRigth() {
      // console.log('存奶')
      this.minML = 10
      this.maxML = 240
      this.indexML = 9
      this.milkInfo = {}
      this.showAddMilk = true
    },
    // 弹窗关闭前调用方法
    beforeClose(action, done) {
      done(false)
    },
    // 刷新前调用
    onLoad() {
      setTimeout(() => {
        if (this.refreshing) {
          // this.list = []
          this.refreshing = false
        }
        // =========== 获取班级列表方法
        this.getList()
        // ===============
        this.loading = false

        if (this.list.length >= 40) {
          this.finished = true
        }
      }, 1000)
    },
    // 刷新列表
    onRefresh() {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    // 处理存奶时间
    chooseAddTime() {
      this.milkInfo.milkDate = this.$parseTime(this.currentDate, '{y}-{m}-{d} {h}:{i}:{s}')
      this.showDatePicker = false
    },
    // 进入详情页
    showDetail(item) {
      this.$router.push({
        name: 'MilkDetail',
        query: {
          id: item.id
        }
      })
    },
    // 存奶弹窗
    addMilk() {
      // console.log('存奶', this.milkInfo)
      const params = JSON.parse(JSON.stringify(this.milkInfo))
      addMilkInfo(params).then((res) => {
        const data = res.data
        console.log('存奶响应', res)
        this.showAddMilk = false
        this.milkInfo = {}
        // 弹出是否再次添加

        this.showAddAgain = true
        this.againMsg = `添加成功！编号为：${data.id}，是否要继续添加？`
        // 刷新列表
        // this.getList()
      })
    },
    clossAddMilk() {
      // console.log('关闭')
      this.showAddMilk = false
      this.milkInfo = {}
    },
    confirmAddAgain() {
      // console.log('确定11')
      this.showAddAgain = false
      this.showAddMilk = true
    },
    // 再次添加
    closeAddAgain() {
      // console.log('关闭11')
      this.showAddAgain = false
      this.getList()
    },
    // 用奶弹窗
    showUseMilkFun(item) {
      this.milkInfo = JSON.parse(JSON.stringify(item))
      this.showUseMilk = true
      console.log('选择', item)
      this.minML = 10
      this.maxML = item.capacity
      this.indexML = 9
    },
    useMilk() {
      if (!this.milkInfo.capacityChoose) {
        Toast('请先选择使用容量')
        return
      }
      const params = {
        id: this.milkInfo.id,
        capacity: this.milkInfo.capacityChoose
      }
      console.log('用后', params)
      useMilk(params).then((res) => {
        Toast('使用成功')
        this.milkInfo = {}
        // 关闭弹窗
        this.showUseMilk = false
        // 刷新列表
        this.getList()
      })
    },
    clossUseMilk() {
      console.log('关闭')
      this.showUseMilk = false
      this.milkInfo = {}
    },

    // 删除按钮执行方法
    deleteMilk(item) {
      Dialog.confirm({
        message: '确定删除吗？'
      }).then(() => {
        // 调用接口
        // console.log('确认删除', item.id)
        const params = {
          id: item.id
        }
        deletedMilkInfo(params).then((res) => {
          Toast('删除成功')
          // console.log(res)
          // 刷新列表
          this.getList()
        })
      }).catch(() => {
        // console.log('取消删除')
      })
      // console.log(item)
    },
    // 搜索框执行方法
    onSearch() {
      console.log(this.key)
      // // 重新渲染列表
      // const patams = {
      //   page: this.currentPage,
      //   size: 10,
      //   key: this.key
      // }
      // getClassList(patams).then((res) => {
      //   console.log(res)
      //   this.list = res.data.list
      //   this.total = res.data.pages
      // })
      this.getList()
    },
    // 请求下一页
    nextPage() {
      this.getList()
    },
    // 获取列表方法
    getList() {
      // 包装参数
      const patams = {
        page: this.currentPage,
        size: this.size,
        key: this.key,
        order: this.filter.order
      }
      if (!patams.key) {
        delete patams.key
      }
      if (this.filter.milkStatus) {
        patams.milkStatus = this.filter.milkStatus
      }
      // 请求接口
      getMilkInfoList(patams).then((res) => {
        // console.log(res)
        this.list = res.data.list
        this.total = res.data.pages
        this.rateInfo = res.data.milkStatistics
        console.log(this.rateInfo)
        this.pageLoading = false
      })
    }

  }
}

</script>

  <style scoped>
.cell_title {
  margin-right: 4px;
  vertical-align: middle;
  font-size: 16px;
  font-weight: 1000;
}
.cell_label {
  font-size: 14px;
  color: gray;
  line-height: 16px;
  font-weight: 500;
}
.right_btn {
  height: 100%;
}
.topShowDiv {
  display: flex;
}
.topShowDiv .crileItem {
  flex: 1;
  margin-top: 20px;
  margin-bottom: 20px;
}
.topShowDiv .crileItem .crileItem_span {
  font-size: 16px;
  font-weight: 1000;
  letter-spacing: 5px;
}
.loading {
  height: 90vh;
  justify-content: center;
}
.crileItem_span_ML {
  font-size: 14px;
  font-weight: 700;
}

/* .listDiv {
    height: 720px;
  } */
  </style>
